<script setup>
import { ref, onMounted,watch,onUnmounted } from "vue";
import axios from "axios";
import conf from "@/conf/conf";
import { ElNotification } from "element-plus";
import router from "@/router";
import { useRoute } from 'vue-router'; 
import { useDetailStore } from "@/store/detail";
import { usePrintStore } from "@/store/print";
import facultyData from "@/util/data";
import { Edit } from "@element-plus/icons-vue";
// 注册printJS
const detail = useDetailStore();
const print = usePrintStore();
const route = useRoute();
const alter=ref(true)
const otherInput = ref([])
// 定义一个响应式的表单数据对象
const formData = ref({
  name: "",
  idCardNumber: "",
  educationLevel: "",
  politicalStatus: "",
  nativePlace: "",
  graduationDate: "",
  studentNumber: "",
  faculty: "",
  major: "",
  transferUnitName: "",
  archiveNumber: "",
  transferType: "",
  expressNumber: "",
  transferDate: "",
  archiveMaterials: "",
});
//数据模型
const data = {
  name: "",
  idCardNumber: "",
  educationLevel: "",
  politicalStatus: "",
  nativePlace: "",
  graduationDate: "",
  studentNumber: "",
  faculty: "",
  major: "",
  transferUnitName: "",
  archiveNumber: "",
  transferType: "",
  expressNumber: "",
  transferDate: "",
  archiveMaterials: "",
};
// 定义输入框列表
const list = [
  { label: "姓名", value: "name" },
  { label: "身份证号", value: "idCardNumber" },
  { label: "学号", value: "studentNumber" },
  { label: "生源地", value: "nativePlace" },
  { label: "学历", value: "educationLevel" },
  { label: "院系", value: "faculty" },
  { label: "专业", value: "major" },
  { label: "政治面貌", value: "politicalStatus" },
  { label: "档案号", value: "archiveNumber" },
  { label: "调档方式", value: "transferType" },
  { label: "快递单号", value: "expressNumber" },
  { label: "转寄单位名称", value: "transferUnitName" },
  { label: "毕业时间", value: "graduationDate" },
  { label: "调档日期", value: "transferDate" },
];
// 定义资料材料选择列表

/** 资料材料选择列表的结构
[{
qualificationName: "资格名称",
materialName: [{
    name: "材料名称",
    checked: false
    },]
otherMaterial:[] //其他材料    
}]
*/
const archiveMaterialsSelectList = ref([]);
let archiveMaterialsList = null;
onMounted(async () => {
  console.log("初始化");
  
  // 获取表单数据
  getFormData()
    .then(() => {
      // 获取用户详情数据
      // 只有在档案信息时才获取用户详情数据
      if (!detail.detailIsEmpty) {
        getUserDetailData();
      }
    })
    .catch((err) => {
      console.log(err);
    });
});
watch(() => route.name, () => {
       // 获取表单数据
      // 获取用户详情数据
      // 只有在档案信息时才获取用户详情数据
      if (!detail.detailIsEmpty) {
        getUserDetailData();
      }
});

onUnmounted(() => {
  console.log("组件销毁");
  useDetailStore().reset()
});
// 获取表单数据
const getFormData = async () => {
  axios({
    method: "get",
    url: `${conf.url}/material`,
  })
    .then((res) => {
      archiveMaterialsList = res.data.data;
      // 遍历资料材料列表，初始化资料材料选择列表
      archiveMaterialsList.forEach((item) => {
        archiveMaterialsSelectList.value.push({
          qualificationName: item.qualificationName,
          materialName: [],
          otherMaterial: []
        });
      });
      // 遍历资料材料列表，初始化资料材料选择列表
      initData(archiveMaterialsList);
    })
    .catch((err) => {
      console.log(err);
    });
};
// 数据初始化
const getUserDetailData = async () => {
  axios({
    method: "get",
    url: `${conf.url}/archive/info`,
    params: {
      id: detail.getDetailId,
    },
  })
    .then((res) => {
      console.log(res.data.data);
      formData.value = res.data.data;
      // 资料材料选择列表选择初始化
      initDetailData();
    })
    .catch((err) => {
      console.log(err);
    });
};

// 初始化资料材料选择列表
const initDetailData = () => {
  archiveMaterialsSelectList.value.forEach((item) => {
    // 1. 获取当前资格的固定材料列表
    const fixedMaterials = archiveMaterialsList.find(
      (m) => m.qualificationName === item.qualificationName
    )?.materialName || [];

    // 2. 获取表单中当前资格的所有材料（假设 materialName 是数组）
    const formMaterials = formData.value.archiveMaterials
      .filter((data) => data.qualificationName === item.qualificationName)
      .flatMap((data) => data.materialName);

    // 3. 生成固定材料列表的选中状态
    const arr = fixedMaterials.map((material) => ({
      name: material,
      checked: formMaterials.includes(material), // 直接检查是否存在
    }));

    // 4. 收集不属于固定列表的材料
    const other = formMaterials.filter(
      (material) => !fixedMaterials.includes(material)
    );

    // 5. 更新数据
    item.materialName = arr;
    item.otherMaterial = other;
  });
};

// 初始化表单数据
const initData = (archiveMaterialsList) => {
  //遍历资料材料选择列表，初始化所有材料为未选择
  archiveMaterialsSelectList.value.forEach((item) => {
    // 遍历资料材料列表，找到该资格名称对应的材料列表
    let node = archiveMaterialsList.find(
      (item2) => item2.qualificationName === item.qualificationName
    ).materialName;
    let arr = [];
    if (node) {
      // 遍历该材料列表，初始化每个材料为未选择
      node.forEach((item2) => {
        arr.push({
          name: item2,
          checked: false,
        });
      });
    }
    // 给该资料材料选择列表的该资格名称的材料列表赋值
    item.materialName = arr;
  });
};

//提交
const handleSubmit = async () => {
  console.log(formData.value);
  // 格式化资料材料选择列表
  formData.value.archiveMaterials = formatArchiveMaterials();
  // 格式化日期
  const date = new Date(formData.value.graduationDate);
  formData.value.graduationDate =
    date.getFullYear() +
    "" +
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1);
  console.log(formData.value);
  if (formData.value.name === "") {
    ElNotification({
      title: "错误",
      message: "请完整填写信息",
      type: "error",
    });
    return;
  }
  console.log("detailIsEmpty", detail.detailIsEmpty);
  
  axios({
    method: !detail.detailIsEmpty ? "put" : "post",
    url: `${conf.url}/archive`,
    data: formData.value,
  })
    .then((res) => {
      console.log(formData.value);
      
      console.log(res);

      //如果是添加档案信息，则重置表单数据，并跳转到档案详情页面
      if (detail.detailIsEmpty) {
        // 重置表单数据
        initData(archiveMaterialsList);
        detail.setDetailId(res.data.data.id);
        initDetailData();
        router.replace("/detail");
      }
       success(detail.detailIsEmpty);
    })
    .catch((err) => {
      console.log(err);
      error();
    });
};

// 资料材料选择事件
const handleSelect = (qualificationName, material) => {
  console.log(archiveMaterialsSelectList.value);
  
  // 查找匹配的资格名称
  const qualification = archiveMaterialsSelectList.value.find(
    (item) => item.qualificationName === qualificationName
  );
  // 查找匹配的材料
  const materialItem = qualification.materialName.find(
    (item) => item.name === material
  );
  // 切换材料的选中状态
  materialItem.checked = !materialItem.checked;
};

//转换选中资料列表格式
const formatArchiveMaterials = () => {
  let arr = [];
  archiveMaterialsSelectList.value.forEach((item) => {
    let obj = {
      qualificationName: item.qualificationName,
      materialName: [],
    };
    item.materialName.forEach((item) => {
      if (item.checked) {
        obj.materialName.push(item.name);
      }
    });
    item.otherMaterial.forEach((item) => {
      obj.materialName.push(item);
    });
    arr.push(obj);
  });
  console.log(arr);
  
  return arr;
};

const handleReset = () => {
  console.log("重置");
  // 重置表单数据
  formData.value = JSON.parse(JSON.stringify(data));
  initData(archiveMaterialsList);
  console.log(formData.value);
};
// 成功提示
const success = (isAdd) => {
  ElNotification({
    title: "成功",
    message:  `${isAdd? "添加" : "修改"}档案信息成功`,
    type: "success",
  });
};

// 错误提示
const error = () => {
  ElNotification({
    title: "错误",
    message: "添加档案信息失败，请检查输入信息",
    type: "error",
  });
};
const toPrint = () => {
  console.log("打印");
  print.setPrintData(formData.value);
  router.push("/print");
};
const querySearch = (string, cb, query) => {
  switch (query) {
    case 4:
      cb(["本科", "硕士", "博士", "博士后"]);
      break;
    case 5:
      cb(facultyData.map((item) => item.faculty));
      break;
    case 6:
      cb(
        facultyData.find((item) => item.faculty === formData.value.faculty)
          .major
      );
      break;
    case 7:
      cb(["群众", "共青团员", "中共党员", "预备党员"]);
      break;
    case 9:
      cb(["快递", "自提"]);
  }
};
const inputOtherMaterial = (index,item) => {
  if(otherInput[index]!== ""){
    item.otherMaterial.push(otherInput.value[index]);
    otherInput.value[index] = "";
    console.log(item.otherMaterial);
    
  }
}
const removeOtherMaterial = (item,tag,index) => {
  console.log(tag);
  item.otherMaterial.splice(index,1);
}
</script>

<template>
  <div>
    <!-- 表单 -->
    <el-form
      :model="formData"
      label-width="100px"
      style="margin-top: 20px"
      :resetField="handleReset"
      id="form"
    >
      <el-row :gutter="24">
        <el-col :span="6" v-for="(item, index) in list" :key="item.value">
          <el-form-item :label="item.label" style="width: 300px">
            <!-- 输入框 -->
            <el-input
              v-model="formData[item.value]"
              v-if="index < 4 || (index > 7 && index < 12 && index !== 9)"
            />
            <el-autocomplete
              v-else-if="(index >= 4 && index < 8) || index === 9"
              v-model="formData[item.value]"
              :fetch-suggestions="
                (queryString, callback) =>
                  querySearch(queryString, callback, index)
              "
              clearable
              @select="formData[item.value] = $event"
              placeholder="请输入"
            >
              <template #suffix>
                <el-icon class="el-input__icon" >
                  <edit />
                </el-icon>
              </template>
              <template #default="{ item }">
                <span @click="formData[item.value] = item">{{ item }}</span>
              </template>
            </el-autocomplete>
            <el-date-picker
              v-else
              v-model="formData[item.value]"
              :type="index === 12 ? 'month' : 'date'"
              :placeholder="
                index === 12 ? '输入格式:YYYY-MM' : '输入格式:YYYY-MM-DD'
              "
              @change="
                () => {
                  console.log(formData[item.value]);
                }
              "
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="alter-border-box" v-if="alter&&route.name!== 'add'">
        <div v-for="(item, index) in archiveMaterialsSelectList" :key="index">
          <div class="alter-module no-print">
            <!-- 资格名称的展示 -->
            <h3>
              {{ item.qualificationName }}
            </h3>
            <p>
              <!-- 材料名称输入标签 -->
                <span v-for="(tag, index) in formatArchiveMaterials()[index].materialName" :key="index" >
                  <span>
                    {{ tag+',' }}
                  </span>
                </span>
            </p>
          </div>
        </div>
      </div>
      <div class="border-box" v-else>
        <el-scrollbar height="340px">
          <!-- 资料材料选择列表 -->
          <div
            class="module no-print"
            v-for="(item, i) in archiveMaterialsSelectList"
            :key="i"
          >
            <!-- 资格名称的展示 -->
            <span class="title">
              {{ item.qualificationName }}
            </span>
            <br /><br />
            <!-- 材料名称输入标签 -->
            <div class="tags">
              <!-- 渲染每个物料名称的标签 -->
              <el-button
                v-for="(tag, index) in item.materialName"
                :key="index"
                style="margin-bottom: 10px; margin-left: 5px"
                size="small"
                @dblclick="handleSelect(item.qualificationName, tag.name)"
                @click="otherInput[i] = tag.name"
                :class="tag.checked ? 'checked' : 'un-checked'"
              >
                {{ tag.name }}
              </el-button>
              <el-button
                v-for="(tag, index) in item.otherMaterial"
                :key="index"
                style="margin-bottom: 10px; margin-left: 5px"
                size="small"
                type="success"
                @click="otherInput[i] = tag"
                @dblclick="removeOtherMaterial(item, tag, index);otherInput[i] = ''"
              >
                {{ tag }}
              </el-button>
            </div>
            <div class="input-box">
              <el-input v-model="otherInput[i]" placeholder="请输入其他材料名称,回车添加" @keydown.enter="inputOtherMaterial(i,item)" />
            </div>
          </div>
        </el-scrollbar>
      </div>
      <el-col :span="6" style="margin-left: 20px">
        <!-- 按钮 -->
        <el-button type="primary" @click="handleSubmit">{{
          !detail.detailIsEmpty ? "提交修改" : "提交"
        }}</el-button>
        <el-button
          type="default"
          @click="handleReset"
          v-if="detail.detailIsEmpty"
          >重置</el-button
        >
        <el-button type="success" @click="toPrint" v-else>打印</el-button>
        <el-button type="default" @click="alter=!alter" v-if="!detail.detailIsEmpty&&route.name!== 'add'">
         <span v-if="alter">
           修改材料
         </span>
         <span v-else>
          关闭修改
         </span>
        </el-button>
       
      </el-col>
    </el-form>
  </div>
</template>
<style scoped>
/* 表单样式 */
.el-form-item {
  margin-bottom: 20px;
  overflow: a;
}
.tags{
  padding:10px;
  height: 210px;
  border: 1px solid #ccc;
  overflow-y: auto;
}
/* 资料材料选择列表样式 */
.border-box {
  width: 97%;
  height: 350px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  justify-content: center;
  align-items: center;
  display: flex;
  margin-bottom: 5px;
  margin-left: 20px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.alter-border-box{
  width: 97%;
  height: 350px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));
  grid-gap: 10px;
  margin-bottom: 5px;
  margin-left: 20px;
  overflow-y: scroll;
  overflow-x: hidden;
}
/* 资料材料选择列表模块样式 */
.module {
  width: 18rem;
  height: 20rem;
  border: 1px solid #ccc;
  margin: 2px;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  padding: 11px;
  display: inline-block;
  transition: all 0.3s ease-in-out;
  background-color: white;
}
.alter-module{
  border: 1px solid #ccc;
  min-height: 10rem;
  padding: 3px;
}
/* 资料材料选择选中样式 */
.checked {
  background-color: #409eff;
  color: white;
}
/* 资料材料选择未选中样式 */
.un-checked {
  background-color: white;
  color: black;
}
.input-box {
  position: relative;
  bottom: 0;
  margin-top: 10px;
}
</style>